<?php


class Gnews_Captcha
{
	protected $session = null;
	protected $key = null;
	protected $options = null;
	
	public function __construct($key, $options = array())
	{
		$this->key = $key;
		$this->options = $options;
		$this->session = new Zend_Session_Namespace( __CLASS__ );
		if( empty($this->session->key)) $this->reset();
	}
	
	function _generateText($key)
	{
		return substr(md5($this->key.$key),0,5);
	}
	public function showimg($reset = true)
	{
		if( $reset ) $this->reset();

		$file_name = dirname(__FILE__)."/Captcha/comic.ttf";
		
		 
		
		
		$text = $this->_generateText($this->session->key);
		// no-cache 
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past 
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified 
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 
		header("Pragma: no-cache"); // HTTP/1.0
		//
		
		header("Content-type: image/png");

		$im = imagecreatetruecolor(135,20);
		
		$c = imagecolorallocate($im, 134,232, 249);
		$white = imagecolorallocate($im, 255, 255, 255);
		imagefilledrectangle($im, 0, 0, 200, 50, $white);
		
		// for debeg imagefttext($im,12,2,12,15,$c,$file_name,$this->session->key);
		for($i=0;$i<5;$i++){
			$a_col = array(0xFF0F0F,0x0F0FFF,0x02F8F0F,0x2F20AF,0xCF4C2F);
			//$black = imagecolorallocate($im, 32,134, 149);
			imagefttext ($im,12+mt_rand(0,2),mt_rand(-25,25),14+$i*23,16,$a_col[$i],$file_name,$text{$i});
		}
		imagepng($im);	
	}
	
	public function valid($key, $reset = true)
	{
		$valid = ($this->_generateText($this->session->key) == $key);
		if( $reset ) $this->reset();
		return $valid;
	}
	
	public function reset()
	{
		$this->session->key = md5(mt_rand(0,0xaFFFFFF).time());
	}
}
?>